package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"gorm.io/gorm"
	"log"
	"mouth-project/model/mysql"
	"mouth-project/request"
	"net/http"
	"strconv"
)

type Node struct {
	Conn    *websocket.Conn
	DataReq chan []byte
}

var Client map[int64]*Node = make(map[int64]*Node, 0)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func Chat(c *gin.Context) {
	id1 := c.Query("UserId1")
	uid1, _ := strconv.Atoi(id1)
	id2 := c.Query("UserId2")
	uid2, _ := strconv.Atoi(id2)
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	node := &Node{
		Conn:    conn,
		DataReq: make(chan []byte, 50),
	}
	Client[int64(uid1)] = node
	SendMessage(node)
	RedMessage(node, int64(uid2))
}

//发送消息

func SendMessage(node *Node) {
	go func() {
		for {
			select {
			case data := <-node.DataReq:
				if err := node.Conn.WriteMessage(websocket.TextMessage, data); err != nil {
					log.Println(err)
					return
				}
			}
		}
	}()
}

//读取消息

func RedMessage(node *Node, userid int64) {
	_, message, err := node.Conn.ReadMessage()
	if err != nil {
		log.Println(err)
		return
	}
	MessageTo(userid, message)
}

//转发消息

func MessageTo(userid int64, message []byte) {
	key, value := Client[userid]
	if value {
		key.DataReq <- message
	}
}
func Delete(c *gin.Context) {
	var chatReq request.ChatDeleteReq
	if err := c.ShouldBindJSON(&chatReq); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "服务器内部错误",
			"code": 500,
			"err":  err.Error(),
		})
		return
	}
	data := mysql.Chat{
		Model: gorm.Model{ID: uint(chatReq.Id)},
	}
	err := data.Delete()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg":  "删除失败",
			"code": 400,
			"err":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "删除成功",
		"code": 200,
		"data": data,
	})
}
